package com.opennews.openplatform

import groovy.transform.CompileStatic
import org.springframework.http.HttpStatus

@CompileStatic
class JoinAccountGroupRequestController extends BaseController {
    static allowedMethods = [
        send: "POST",
        accept: "POST",
        reject: "POST",
        delete: "POST"
    ]

    JoinAccountGroupRequestService joinAccountGroupRequestService

    // region: Get actions.
    def index() {
        render("JoinAccountGroupRequestController")
    }

    def countReceived() {
        def userId = getClaims().id
        def result = joinAccountGroupRequestService.countReceived(userId)

        sendDataResponse([count: result])
    }

    def queryReceiving() {
        def pageSize = params.int("pageSize")
        def pageIndex = params.int("pageIndex")
        def id = getClaims().id
        def result = joinAccountGroupRequestService.queryReceiving(id, pageSize, pageIndex)

        sendDataResponse(result)
    }
    // endregion

    // region: Post actions.
    def send() {
        def requestBodyData = getRequestBodyData()
        def receiverId = requestBodyData.receiverId.toString()
        def roles = requestBodyData.roles as List<String>

        def claims = getClaims()
        def senderId = claims.id
        def accountGroupId = claims.accountGroupId
        joinAccountGroupRequestService.addOrUpdate(accountGroupId, senderId, receiverId, roles)

        sendStatusResponse(HttpStatus.NO_CONTENT)
    }

    def accept() {
        def requestBodyData = getRequestBodyData()
        def id = requestBodyData.id.toString()
        def receiverId = getClaims().id
        joinAccountGroupRequestService.accept(id, receiverId)

        sendStatusResponse(HttpStatus.NO_CONTENT)
    }

    def reject() {
        def requestBodyData = getRequestBodyData()
        def id = requestBodyData.id.toString()
        def receiverId = getClaims().id
        joinAccountGroupRequestService.reject(id, receiverId)

        sendStatusResponse(HttpStatus.NO_CONTENT)
    }

    def delete() {
        // By now rejecting and deleting follow the same logic.
        // But you can distinguish it as you need.
        def requestBodyData = getRequestBodyData()
        def id = requestBodyData.id.toString()
        def receiverId = getClaims().id
        joinAccountGroupRequestService.reject(id, receiverId)

        sendStatusResponse(HttpStatus.NO_CONTENT)
    }
    // endregion
}
